//
//  AiNetworkManager.m
//  ROSE
//
//  Created by 艾阳 on 2018/5/22.
//  Copyright © 2018年 HeNanZhongDunYunAn. All rights reserved.
//

#import "AiNetworkManager.h"


@implementation AiNetworkManager

#pragma mark POST/GET

- (void)POST:(NSString *)urlString parameters:(id)parameters completion:(void (^)(AiBaseResponse *))completion
{
    [self request:@"POST" URL:urlString parameters:parameters completion:completion];
}

- (void)GET:(NSString *)urlString parameters:(id)parameters completion:(void (^)(AiBaseResponse *))completion{
    [self request:@"GET" URL:urlString parameters:parameters completion:completion];
}

#pragma mark Request
- (void)request:(NSString *)method URL:(NSString *)urlString parameters:(id)parameters completion:(void(^)(AiBaseResponse *response))completion{
    if (self.isLocal) {
        [self requestLocal:urlString completion:completion];
        return;
    }
    if (self.reachabilityManager.networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
        AiBaseResponse *response = [AiBaseResponse new];
        response.error = [NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:nil];
        response.errorMsg = @"网络无法连接";
        completion(response);
        return;
    }
    
    /**
     成功Block
     */
    void(^success)(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) = ^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //[self wrapperTask:task responseObject:responseObject error:nil completion:completion];
    };
    
    /**
     失败Block
     */
    void(^failure)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //[self wrapperTask:task responseObject:nil error:error completion:completion];
    };
    
    if ([method isEqualToString:@"GET"]) {
        [self GET:urlString parameters:parameters progress:nil success:success failure:failure];
    }
    if ([method isEqualToString:@"POST"]) {
        [self POST:urlString parameters:parameters progress:nil success:success failure:failure];
    }
    
}

#pragma mark LocalRequest 加载本地数据
- (void)requestLocal:(NSString *)urlString completion:(void (^)(AiBaseResponse *response))completion{
    
}
#pragma mark - 处理数据
- (void)wrapperTask:(NSURLSessionDataTask *)task responseObject:(id)responseObject error:(NSError *)error completion:(void (^)(AiBaseResponse *response))completion{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        AiBaseResponse *response = [self convertTask:task responseObject:responseObject error:error];
        [self LogResponse:task.currentRequest.URL.absoluteString response:response];
        dispatch_async(dispatch_get_main_queue(), ^{
            !completion?:completion(response);
        });
    });
}



#pragma mark - 包装返回的数据
- (AiBaseResponse*)convertTask:(NSURLSessionDataTask *)task responseObject:(id)responseObject error:(NSError *)error{
    AiBaseResponse *response = [AiBaseResponse new];
    
    if (!IsEmpty(responseObject)) {
        response.responseObject = responseObject;
    }
    if (error) {
        response.error = error;
    }
    if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *)task.response;
        response.headers = HTTPURLResponse.allHeaderFields.mutableCopy;
    }
    if (self.responseFormat) {
        response = self.responseFormat(response);
    }
    return response;
}
#pragma mark - 打印返回日志
- (void)LogResponse:(NSString *)urlString response:(AiBaseResponse *)response{
    NSLog(@"\n[%@]---%@\n",urlString,response);
}

#pragma mark - configSettings
- (void)configSettings{
    //设置可接收的数据类型
    NSMutableSet *acceptableContentTypes = [NSMutableSet setWithSet:self.responseSerializer.acceptableContentTypes];
    [acceptableContentTypes addObjectsFromArray:@[@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"application/xml", @"text/xml", @"*/*", @"application/x-plist"]];
    self.responseSerializer.acceptableContentTypes = [acceptableContentTypes copy];
    
    //记录网络状态
    [self.reachabilityManager startMonitoring];
    //自定义处理数据
    //self.responseFormat = ^AiBaseResponse *(AiBaseResponse *response) {
      //  return response;
    //};
}


+ (instancetype)manager{
    AiNetworkManager *manager = [super manager];
    [manager configSettings];
    return manager;
}

static AiNetworkManager * _instance = nil;

+ (instancetype)sharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [self manager];
    });
    return _instance;
}

@end
